<?php
declare (strict_types=1);

namespace app\admin\model\iot;

use app\BaseModel;

/**
 * 积分订单
 */
class IntegralOrder extends BaseModel
{

    protected $autoWriteTimestamp =true;
    /**
     * 积分任务列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @param string $orderby
     * @param string $field
     * @return array
     */
    public static function getList(array $where, int $page=1, int $limit=100, string $orderby = '', string $field = '*'): array
    {
        $data = self::field($field)
            ->where($where)
            ->order($orderby)
            ->paginate(['list_rows' => $limit, 'page' => $page], false)
            ->toArray();
        return $data;
    }

    public static function getTaskInfo(int $task_id): array
    {
        //查询数据库
        $field = 'id,name,type,bonus_points,jump_url,mini_jump_url,official_id,enabled,num';
        $data = self::field($field)
            ->where(['id' => $task_id])
            ->cache(true, 60)
            ->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 设备注册
     * @param array $params
     * @return array
     */
    public static function deviceRegister(array $params): array
    {
        //验证设备类型参数
        if (!array_key_exists($params['type'], self::$deviceTypeArr)) {
            return [];
        }
        //初始化参数
        $params['last_time'] = time();
        $params['update_time'] = time();
        //获取当前设备是否存在
        $where = ['imei' => $params['imei'], 'closed' => 0];
        $model = self::where($where)->find();
        if (!$model) {
            //不存在则新增设备
            $params['mac_id'] = self::generateMacId($params['type']);
            $params['install'] = 0;
            $params['create_time'] = time();
            $model = new self();
        }
        //写入数据库
        $bool = $model->save($params);
        if ($bool) {
            return $model->toArray();
        }
        return [];
    }

    /**
     * 生成mac_id
     * @param int $type
     * @return string
     */
    private static function generateMacId(int $type): string
    {
        //查询当前类型的最后一条
        $mac_id = self::where(['type' => $type])->where('mac_id','like',$type."10%")->order('mac_id', 'desc')->limit(1)->value('mac_id');
        if ($mac_id) {
            $mac_id = intval(substr(strval($mac_id), strlen(strval($type)))) + 1;
            $mac_id = intval($type . $mac_id);
        } else {
            $mac_id = intval($type . '10001');
        }
        return strval($mac_id);
    }

    /**
     * 写入设备袋子余量
     * @param string $imei
     * @param int $allowance
     * @return bool
     */
    public static function deviceAllowance(string $imei, int $allowance = 0): bool
    {
        //更新设备表
        self::update(['allowance' => $allowance], ['imei' => $imei]);
        return true;
    }

}




